import uuid

from django.http import JsonResponse
from django.shortcuts import render,redirect
from django.urls import reverse
from django.db.models import Q
import requests
from django.core.files.base import ContentFile
from Nav.get_web_card import get_website_business_card
from Nav.models import Category, Nav, ImagesModel
from django.contrib.auth import logout
from django.forms.models import model_to_dict
from django.contrib.auth.decorators import login_required



# Create your views here.
from django.core import serializers

def index(request):
    categories = Category.objects.filter(is_show=True)
    is_show_admin = request.user.is_authenticated and request.user.is_staff
    context = {
        "web_title": "尧-导航",
        "web_desc": "",
        "categories": categories,
        "is_show_admin": is_show_admin,
    }
    return render(request, 'index.html', context=context)


def search(request):
    keywords = request.GET.get('keywords')
    categories_navs = {}

    is_show_admin = request.user.is_authenticated and request.user.is_staff
    if is_show_admin:
        navs = Nav.objects.filter(Q(category__is_show=True),
                                             Q(name__contains=keywords)
                                             |Q(description__contains=keywords))
    else:
        navs = Nav.objects.filter(Q(category__is_show=True),
                                  Q(permission=False),
                                  Q(name__contains=keywords)
                                  | Q(description__contains=keywords))

    for nav_item in navs:
        nav_dict = model_to_dict(nav_item)
        nav_dict.update({"image":{"url":nav_item.image.image.url}})
        navs_list = categories_navs.get(nav_item.category.name, [])
        navs_list.append(nav_dict)
        categories_navs.update({nav_item.category.name:navs_list})

    context = {
        "navs": categories_navs,
    }
    return JsonResponse(context)


def auto_update_nav(request):
    is_show_admin = request.user.is_authenticated and request.user.is_staff
    if not is_show_admin:
        return redirect('/admin/login/')

    if request.method == 'GET':
        categories = Category.objects.all()
        return  render(request, 'auto_update_nav.html',locals())
    elif request.method == 'POST':

        is_show = request.POST.get('is_show')
        categories = request.POST.get('categories')
        url = request.POST.get('url')
        Nav_model = Nav()
        Nav_model.url = url
        Nav_model.is_show = is_show
        Nav_model.category = Category.objects.get(id=categories)
        web = {}
        if url:
            web = get_website_business_card(url)
            if web:
                # 下载logo
                if web.get("logo", None):
                    headers = {
                        'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.119 Safari/537.36'}
                    file_format = '.' + web["imageformat"] if web["imageformat"] else ".jpg"
                    random_name = web["title"] + str(uuid.uuid4()) + file_format \
                        if web["title"] is not None else str(
                        uuid.uuid4()) + file_format
                    response = requests.get(web["logo"], headers=headers)
                    if response.status_code == 200:
                        image_model = ImagesModel()
                        image_model.image.save(random_name, ContentFile(response.content))
                        image_model.save()
                        Nav_model.image = image_model
                Nav_model.name = web.get("title", "None")
                Nav_model.description = web.get("description", "None")
                Nav_model.save()
                return JsonResponse(model_to_dict(Nav_model))
        return JsonResponse({"success":False})

def logouts(request):
    logout(request)
    response = redirect(reverse('index'))
    # 退出登录时清除cookie中的登录状态
    response.delete_cookie('is_login')

    return response
